﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;

public class A_Sc : MonoBehaviour {

    public GameObject buttonScreenShot;
    public GameObject QRPanel;

    public GameObject panel;

    public Text countText;

    public bool count = false;

    private int i = 0;

    private int countTime = 5;

    public Texture2D Te2D;

    public string uploadURL= "http://39.98.84.136/UpLoadAR.aspx";

    public Text Tx_AIn_In;

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    private void FixedUpdate()
    {
        if (count)
        {
            i++;

            countText.text = countTime.ToString();
            if (i > 30 && i < 60)
            {
                countTime = 4;
            }
            if (i > 60 && i < 90)
            {
                countTime = 3;
            }
            if (i > 90 && i < 120)
            {
                countTime = 2;
            }
            if (i > 120 && i < 150)
            {
                countTime = 1;
            }
            if (i > 150 && i < 180)
            {
                countTime = 0;
            }
            if (i ==200)
            {
                panel.SetActive(false);
                count = false;
                buttonScreenShot.SetActive(false);
                ScreenShot();
            }
        }
    }

    public void CountStart()
    {
        countTime = 5;
        i = 0;
        count = true;
        panel.SetActive(true);
    }

    private void ScreenShot()
    {
        QRPanel.SetActive(true);
        StartCoroutine(WaitFrameBuffer());
    }

    IEnumerator WaitFrameBuffer()
    {
        yield return new WaitForEndOfFrame();
        Te2D = new Texture2D(1600, 900, TextureFormat.RGB24, true);
        Te2D.ReadPixels(new Rect(160, 140, 1600, 900), 0, 0, true);
        Te2D.Apply();

        byte[] bytes = Te2D.EncodeToJPG();

        WWWForm wwwForm = new WWWForm();

        wwwForm.AddBinaryData("post", bytes);

        WWW www = new WWW(uploadURL, wwwForm);

        StartCoroutine(PostImage(www));
    }

    IEnumerator PostImage(WWW www)
    {
        yield return www;
        Tx_AIn_In.text = www.text;
    }
}
